#include "StdAfx.h"
#include ".\connectthread.h"
#include "Connection.h"
#include "CompletionPort.h"

namespace Lumin {
namespace Win32 {

CConnectThread::CConnectThread(const char* address,unsigned short port,DWORD dwContext,CServer* pServer):m_address(address),m_port(port),m_dwContext(dwContext),m_pServer(pServer)
{
}

CConnectThread::~CConnectThread(void)
{
}

int CConnectThread::Run()
{
	SOCKET skClient = CSocket::ConnectToServer(m_port,m_address.c_str()); 
	if(skClient != INVALID_SOCKET)
	{
		CConnection* pConnection = new CConnection(m_address.c_str(),m_dwContext);
		if(pConnection != NULL)
		{
			CIOContext* pIOContext = new CIOContext();
			pIOContext->stream = CServer::Allocate();
			pIOContext->stream->AddRef();
			pIOContext->iop = WSA_IO_ACCEPT;
			pIOContext->conn = pConnection;
			pConnection->AttachSocket(skClient);
			CCompletionPort::GetInstance()->PostQueuedCompletionStatus((ULONG_PTR)pConnection,0,&pIOContext->overlapped);
		}else{
			m_pServer->OnConnectFailed(m_dwContext);
			closesocket(skClient);
			skClient = INVALID_SOCKET;
			//CCompletionPort::GetInstance()->PostQueuedCompletionStatus((ULONG_PTR)pConnection,0,&pIOContext->overlapped);
		}
	}
	else
	{
		m_pServer->OnConnectFailed(m_dwContext);
	}
	delete this;
	return 0;
}

}
}